program define balplot_cat
   * bonf is number of tests (for bonferroni ci). Default = 1.	
   version 16.1
	syntax varname [pweight], tlabels(str) gopts(str) [BONF(int 1)] cat1(str) title1(str) ///
	   cat2(str) title2(str) [cat3(str) title3(str) cat4(str) title4(str) byopts(str)]
   di "Pweight is `weight'"
	* local cilevel = round(100 - 5/`bonf',0.01) // bonferroni confidence level
	local cilevel = round(100 - 5/`bonf',0.1) // bonferroni confidence level
	di `cilevel'
	local ncats : word count `cat1' `cat2' `cat3' `cat4' // number of cat levels
	forvalues i = 1/`ncats' {
	   tempname y`i'
	   qui gen `y`i'' = cond(`varlist'==`cat`i'', 100, 0)
	   reg `y`i'' i.t [`weight'`exp']
	   margins i.t, level(`cilevel')
	   tempname fx`i'
      matrix `fx`i'' = r(table)		
      matrix colnames `fx`i'' = `tlabels'
      reg `y`i'' [`weight'`exp']
      local xline`i' = _b[_cons]
	   mat list `fx`i''
		local plot`i' (matrix(`fx`i''[1,]), ci("`fx`i''[5,] `fx`i''[6,]")), bylabel(`title`i'')  || 
   }
   #delimit ;
	coefplot `plot1' `plot2' `plot3' `plot4', xlabel(0(20)100) mlabel format(%2.0f) mlabpos(12)
	   order(
		      a0_s0 a0_s1 a1_s0 a1_s1 a2_s0 a2_s1 
		      /* a2_s2 */	
				a0_s4 a1_s4 a2_s4
				a0_s3 a1_s3 a2_s3 
				a1_s5 a1_s6 a1_s7 a1_s8 a1_s9
		)		  
	   heading(a0_s0 = "{bf:Experiment 1}" /* a2_s2 = "{bf:Experiment 2}" */
		   a0_s4 = "{bf:Experiment 2}" a0_s3 = "{bf:Experiment 3}" 
			a1_s5 = "{bf:Experiment 4}")
	   coeflabel(
		   a0_s0 = "No Action, No Shaming" 
			a0_s1 = "No Action, Shaming" 
			a1_s0 = "Cut 5%, No Shaming" 
		   a1_s1 = "Cut 5%, Shaming" 
			a2_s0 = "Cut 25%, No Shaming" 
			a2_s1 = "Cut 25%, Shaming" 
			a2_s2 = "Cut 25%, Praise"
			a0_s3 = "No Action, Shaming + Defiance" 
			a1_s3 = "Cut 5%, Shaming + Defiance" 
			a2_s3 = "Cut 25%, Shaming + Defiance" 
			a0_s4 = "No Action, Shaming + Contrition" 
			a1_s4 = "Cut 5%, Shaming + Contrition" 
			a2_s4 = "Cut 25%, Shaming + Contrition" 
			a1_s5 = "Cut 5%, No Shaming"
			a1_s6 = "Cut 5%, Many Countries"
			a1_s7 = "Cut 5%, Allies Only"
			a1_s8 = "Cut 5%, Non-Allies Only"
			a1_s9 = "Cut 5%, Allies & Non-Allies"
		)
      scheme(s1mono) plotregion(style(none) margin(b+2)) byopts(`byopts') `gopts';
   #delimit cr		  
	forvalues i = 1/`ncats' {
	   addplot `i': , xline(`xline`i'', lpattern(dash) lcolor(gs12)) norescaling
	}
	
end
